package com.mengshu.token.interceptor;

import com.mengshu.token.properties.TokenConfig;
import com.mengshu.token.utils.TokenConfigUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@RequiredArgsConstructor
public class PermissionWebMvcConfigurer implements WebMvcConfigurer {

    private final TokenConfigUtils tokenConfigUtils;

    private final PermissionHandlerInterceptor permissionHandlerInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        final InterceptorRegistration interceptorRegistration = registry.addInterceptor(permissionHandlerInterceptor);
        if (!tokenConfigUtils.isMultiTokenConfig()) {
            String[] excludes = new String[0];
            TokenConfig tokenConfig = tokenConfigUtils.getDefaultConfig();
            if (tokenConfig.getExcludes() != null) {
                excludes = tokenConfig.getExcludes().split(",");
            }
            interceptorRegistration.excludePathPatterns(excludes);
        }
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(permissionHandlerInterceptor);
    }
}
